package com.github.freewu.commons.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import org.greenrobot.greendao.DbUtils;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseOpenHelper;
import org.greenrobot.greendao.generator.DaoUtil;

import java.io.IOException;

/**
 * 数据库链接工具
 * Created by free on 16-9-19.
 */
public class DBHelper extends DatabaseOpenHelper {
    private Context context;

    private String path;

    private OnUpdateDbListener dbListener;

    public DBHelper(Context context, String name, int version) {
        super(context, name, version);
    }

    public DBHelper(Context context, String name, int version, String path) {
        super(context, name, version);

        this.context = context;

        this.path = path;
    }

    public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }


    @Override
    public void onCreate(Database db) {
        super.onCreate(db);

        if (TextUtils.isEmpty(path)) {
            return;
        }
        try {
            DbUtils.executeSqlScript(context, db, path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(Database db, int oldVersion, int newVersion) {
        super.onUpgrade(db, oldVersion, newVersion);

        if (dbListener != null) {
            dbListener.update(db, oldVersion, newVersion);
        }
    }

    public void setDbListener(OnUpdateDbListener dbListener) {
        this.dbListener = dbListener;
    }
}
